from django import forms
from django.core.exceptions import ValidationError
from .models import Recipe, RecipeImage, Tag, Category

class RecipeForm(forms.ModelForm):
    tags = forms.ModelMultipleChoiceField(
        queryset=Tag.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=False
    )
    # images = forms.FileField(
    #     widget=MultiFileInput(attrs={'multiple': True}),
    #     required=False
    # )

    class Meta:
        model = Recipe
        fields = [
            'title', 'description', 'ingredients', 'steps', 'notes', 'link',
            'tags', 'category', 'location', 'shop_name',
            'rating', 'difficulty', 'estimated_minutes', 'price_tier',
            'is_takeaway_available', 'health_index'
        ]
        widgets = {
            'title': forms.TextInput(attrs={'class': 'form-control'}),
            'description': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
            'ingredients': forms.Textarea(attrs={'class': 'form-control', 'rows': 4}),
            'steps': forms.Textarea(attrs={'class': 'form-control', 'rows': 6}),
            'notes': forms.Textarea(attrs={'class': 'form-control', 'rows': 3}),
            'link': forms.URLInput(attrs={'class': 'form-control'}),
            'category': forms.Select(attrs={'class': 'form-control'}),
            'location': forms.TextInput(attrs={'class': 'form-control'}),
            'shop_name': forms.TextInput(attrs={'class': 'form-control'}),
            'rating': forms.NumberInput(attrs={'class': 'form-control', 'min': 0, 'max': 5, 'step': 0.1}),
            'difficulty': forms.Select(attrs={'class': 'form-control'}),
            'estimated_minutes': forms.NumberInput(attrs={'class': 'form-control', 'min': 1}),
            'price_tier': forms.Select(attrs={'class': 'form-control'}),
            'is_takeaway_available': forms.CheckboxInput(attrs={'class': 'form-check-input'}),
            'health_index': forms.NumberInput(attrs={'class': 'form-control', 'min': 1, 'max': 5}),
        }

    def clean(self):
        cleaned = super().clean()
        category = cleaned.get('category')
        location = cleaned.get('location', '').strip()
        shop_name = cleaned.get('shop_name', '').strip()
        is_takeaway_available = cleaned.get('is_takeaway_available')

        # 如果 category 明确为 "堂食"，要求填写位置
        if category and category.name == '堂食' and not location:
            raise ValidationError("选择了“堂食”分类，需要填写位置（location）。")

        # 如果 category 明确为 "外卖"，要求填写店铺名
        if category and category.name == '外卖' and not shop_name:
            raise ValidationError("选择了“外卖”分类，需要填写店铺名称（shop_name）。")

        # 如果标记为不可外卖但分类是外卖，给个提示（但允许）
        if category and category.name == '外卖' and not is_takeaway_available:
            # 不抛出错误，仅作为警告：这里可以把它放到cleaned_data里或前端提示。为了简单，赋值为 True。
            cleaned['is_takeaway_available'] = True

        return cleaned
